local lume = require('lib.lume')

return Class {
   _name = "Upool",
   init = function (self, umax)
      self.umax = umax or 500
      self.pool = {}
   end,

   update = function (self, dt)
      lume.each(self.pool, function (v) if not v.inactive then v:update(dt) end end)
   end,

   draw = function (self)
      lume.each(self.pool, function (v) if not v.inactive then v:draw() end end)
   end,

   get_id = function (self, u)
      return lume.find(self.pool, u)
   end,

   add = function (self, t)
      if not (t._name == "Unit") then  error("Assertion failed: t._name == \"Unit\"")  end
      if #self.pool <= self.umax then
	 lume.push(self.pool, t)
      else
	 for i, v in ipairs(self.pool) do
	    if v.inactive then
	       v = t
	       return v
	    end
	 end
      end
   end,

   _offset_data = function () --WARNING destructive!
      for i = #self.pool, 2, -1 do
	 self.pool[i-1] = self.pool[i]
      end
      self.pool[1] = nil
   end,

   unit_at = function (self, x, y)
      return lume.match(self.pool, function (v) return v.x == x and v.y == y end)
   end,

   find_selected = function (self)
      for i, u in ipairs(self.pool) do
	 if u.selected then return u end
      end
   end,

   get_next_unit = function (self, _u)
      local __u = self:find_selected()
      local u_id = lume.find(self.pool, __u)
      local next_u_id
      if u_id >= #self.pool then
	 next_u_id = 1
      else
	 next_u_id = u_id + 1
      end
      return self.pool[next_u_id]
   end,

   get_selected = function (self)
      for k, v in ipairs(self.pool) do
	 if v.selected then return v end
      end
   end,
}
